package com.elm_springboot_s.mapper;

import com.elm_springboot_s.pojo.Orders;
import com.elm_springboot_s.pojo.OrderDetailet;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface OrdersMapper {
    
    @Insert("INSERT INTO orders (userId, businessId, orderDate, orderTotal, daId, orderState) " +
            "VALUES (#{userId}, #{businessId}, NOW(), #{orderTotal}, #{daId}, 0)")
    @Options(useGeneratedKeys = true, keyProperty = "orderId")
    int saveOrders(Orders orders);
    
    @Insert("INSERT INTO orderdetailet (orderId, foodId, quantity) " +
            "SELECT #{orderId}, foodId, quantity FROM cart " +
            "WHERE userId = #{userId} AND businessId = #{businessId}")
    int saveOrderDetailetFromCart(Integer orderId, Long userId, Integer businessId);
    
    @Delete("DELETE FROM cart WHERE userId = #{userId} AND businessId = #{businessId}")
    int removeCart(Long userId, Integer businessId);
    
    @Select("SELECT o.*, b.businessName, b.businessAddress " +
            "FROM orders o LEFT JOIN business b ON o.businessId = b.businessId " +
            "WHERE orderId = #{orderId}")
    @Results({
        @Result(property = "orderId", column = "orderId"),
        @Result(property = "orderDetailetList", column = "orderId", 
                many = @Many(select = "getOrderDetailetByOrderId"))
    })
    Orders getOrdersById(Integer orderId);
    
    @Select("SELECT od.*, f.foodName, f.foodImg, f.foodPrice " +
            "FROM orderdetailet od " +
            "LEFT JOIN food f ON od.foodId = f.foodId " +
            "WHERE od.orderId = #{orderId}")
    List<OrderDetailet> getOrderDetailetByOrderId(Integer orderId);
    
    @Select("SELECT o.*, b.businessName, b.businessAddress " +
            "FROM orders o LEFT JOIN business b ON o.businessId = b.businessId " +
            "WHERE userId = #{userId}")
    @Results({
        @Result(column = "orderId", property = "orderDetailetList", 
                many = @Many(select = "getOrderDetailetByOrderId"))
    })
    List<Orders> listOrdersByUserId(Long userId);
} 